package com.hutou.chuangke.activity;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bilibili.magicasakura.utils.ThemeUtils;
import com.google.gson.JsonObject;
import com.hutou.chuangke.Bean.UserBean;
import com.hutou.chuangke.MainApplication;
import com.hutou.chuangke.R;
import com.hutou.chuangke.adapter.MenuItemAdapter;
import com.hutou.chuangke.dialog.CardPickerDialog;
import com.hutou.chuangke.fragment.BitSetFragment;
import com.hutou.chuangke.fragment.MainFragment;
import com.hutou.chuangke.fragment.TimingFragment;
import com.hutou.chuangke.fragmentnet.HistoryFragment;
import com.hutou.chuangke.fragmentnet.IndexFragment;
import com.hutou.chuangke.fragmentnet.TabNetPagerFragment;
import com.hutou.chuangke.fragmentnet.TrackFragment;
import com.hutou.chuangke.handler.HandlerUtil;
import com.hutou.chuangke.net.HttpUtil;
import com.hutou.chuangke.net.NetworkUtils;
import com.hutou.chuangke.net.RequestThreadPool;
import com.hutou.chuangke.net.http.User;
import com.hutou.chuangke.service.MusicPlayer;
import com.hutou.chuangke.uitl.BroadcastString;
import com.hutou.chuangke.uitl.LogUtil;
import com.hutou.chuangke.uitl.SharedPreferencesUtil;
import com.hutou.chuangke.uitl.ThemeHelper;
import com.hutou.chuangke.uitl.Utils;
import com.hutou.chuangke.widget.CircleImageView;
import com.hutou.chuangke.widget.CustomViewPager;
import com.hutou.chuangke.widget.SplashScreen;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.message.PushAgent;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity implements CardPickerDialog.ClickListener, View.OnClickListener {
    private String TAG = "MainActivity";
    private ActionBar ab;
    private ImageView barindex, barhistory, bartrack, search;
    private CheckBox checkbox;
    private ArrayList<ImageView> tabs = new ArrayList<>();
    private DrawerLayout drawerLayout;
    private ListView mLvLeftMenu;
    private long time = 0;
    private SplashScreen splashScreen;
    private Context mContext;
    private RelativeLayout login_regitser_layout,download_layout,
            collection_layout,message_layout,bundAccount_layout,
            cleanCash_layout,about_layout,version_layout,
            feedback_layout,loginOut_layout;
    private CircleImageView head_iv,small_head_iv;
    private TextView username_tv;
    private TextView username_motto;
    private String username,password;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private UserBean user;
    private PushAgent mPushAgent;
    private Requestgetuserinfo requestgetuserinfo;
    private RelativeLayout left_layout;
    private static final int LOGIN_REGISTER_REQUEST = 101;


    public void onCreate(Bundle savedInstanceState) {
        splashScreen = new SplashScreen(this);
        splashScreen.show(R.drawable.huanyingye,
                SplashScreen.SLIDE_LEFT);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;
        HandlerUtil.getInstance(this).postDelayed(new Runnable() {
            @Override
            public void run() {
                splashScreen.removeSplashScreen();
            }
        }, 3000);
        sharedPreferencesUtil = new SharedPreferencesUtil();
        username = (String) sharedPreferencesUtil.getData(mContext,
                SharedPreferencesUtil.USER_NAME,"");
        password = (String) sharedPreferencesUtil.getData(mContext,
                SharedPreferencesUtil.PASS_WORD,"");
        getWindow().setBackgroundDrawableResource(R.color.background_material_light_1);

        initView();
        initReciver();
        setToolBar();
        setViewPager();
        initData();
        initUmeng();
    }

    private void initReciver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(BroadcastString.UPDATE_USER_INFO);
        //注册广播

        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    private void initView() {
        barindex = (ImageView) findViewById(R.id.bar_net);
        barhistory = (ImageView) findViewById(R.id.bar_music);
        bartrack = (ImageView) findViewById(R.id.bar_friends);
        search = (ImageView) findViewById(R.id.bar_search);
        barhistory = (ImageView) findViewById(R.id.bar_music);
        drawerLayout = (DrawerLayout) findViewById(R.id.fd);
        head_iv = (CircleImageView) findViewById(R.id.head_iv);
        left_layout = (RelativeLayout) findViewById(R.id.left_layout);
        left_layout.setOnClickListener(this);
        small_head_iv = (CircleImageView) findViewById(R.id.small_head_iv);
        small_head_iv.setOnClickListener(this);
        username_tv = (TextView) findViewById(R.id.username_tv);
        username_motto = (TextView) findViewById(R.id.username_motto);
        login_regitser_layout = (RelativeLayout) findViewById(R.id.login_regitser_layout);
        login_regitser_layout.setOnClickListener(this);
        download_layout = (RelativeLayout) findViewById(R.id.download_layout);
        download_layout.setOnClickListener(this);
        collection_layout = (RelativeLayout) findViewById(R.id.collection_layout);
        collection_layout.setOnClickListener(this);
        message_layout = (RelativeLayout) findViewById(R.id.message_layout);
        message_layout.setOnClickListener(this);
        bundAccount_layout = (RelativeLayout) findViewById(R.id.bundAccount_layout);
        bundAccount_layout.setOnClickListener(this);
        cleanCash_layout = (RelativeLayout) findViewById(R.id.cleanCash_layout);
        cleanCash_layout.setOnClickListener(this);
        about_layout = (RelativeLayout) findViewById(R.id.about_layout);
        about_layout.setOnClickListener(this);
        version_layout = (RelativeLayout) findViewById(R.id.version_layout);
        version_layout.setOnClickListener(this);
        feedback_layout = (RelativeLayout) findViewById(R.id.feedback_layout);
        feedback_layout.setOnClickListener(this);
        loginOut_layout = (RelativeLayout) findViewById(R.id.loginOut_layout);
        loginOut_layout.setOnClickListener(this);
        checkbox = (CheckBox) findViewById(R.id.checkbox);
    }

    private void initUmeng() {
        mPushAgent = PushAgent.getInstance(this);
        mPushAgent.onAppStart();
    }

    private void initData() {
        if(!password.isEmpty()) {
            loginRequest();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == LOGIN_REGISTER_REQUEST){

            loginRequest();
//            if(resultCode == Activity.RESULT_OK){
//                user = (UserBean) data.getSerializableExtra("user");
//                if(user!=null) {
//                    reUserUI();
//                }
//            }
        }
    }

    /**更新用户信息*/
    private void reUserUI() {
        if(user!=null) {
            ImageLoader.getInstance().displayImage(user.getUserimgurl(), head_iv);
            ImageLoader.getInstance().displayImage(user.getUserimgurl(), small_head_iv);
            username_tv.setText(user.getSinger());
            username_motto.setVisibility(View.VISIBLE);
            username_motto.setText(user.getMotto());
        }
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(action.equals(BroadcastString.UPDATE_USER_INFO)){
                requestgetuserinfo = new Requestgetuserinfo();
                requestgetuserinfo.execute();
            }
        }

    };

    private void setToolBar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
//        ab = getSupportActionBar();
//        ab.setDisplayHomeAsUpEnabled(true);
//        ab.setHomeAsUpIndicator(R.drawable.nav_home_me_bg);
//        ab.setTitle("11");
    }

    private void setViewPager() {
        tabs.add(barindex);
        tabs.add(barhistory);
        tabs.add(bartrack);
        final CustomViewPager customViewPager = (CustomViewPager) findViewById(R.id.main_viewpager);
        final MainFragment mainFragment = new MainFragment();
        final TabNetPagerFragment tabNetPagerFragment = new TabNetPagerFragment();
        CustomViewPagerAdapter customViewPagerAdapter = new CustomViewPagerAdapter(getSupportFragmentManager());
//        customViewPagerAdapter.addFragment(tabNetPagerFragment);
//        customViewPagerAdapter.addFragment(mainFragment);
        final IndexFragment indexFragment = new IndexFragment();
        final HistoryFragment historyFragment = new HistoryFragment();
        final TrackFragment trackFragment = new TrackFragment();
        customViewPagerAdapter.addFragment(indexFragment);
        customViewPagerAdapter.addFragment(mainFragment);
//        customViewPagerAdapter.addFragment(tabNetPagerFragment);
        customViewPagerAdapter.addFragment(trackFragment);

        customViewPager.setOffscreenPageLimit(2);//缓存2个+1个显示
        customViewPager.setAdapter(customViewPagerAdapter);
        customViewPager.setCurrentItem(0);
        barindex.setSelected(true);
        customViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switchTabs(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        barindex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customViewPager.setCurrentItem(0);
            }
        });
        barhistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customViewPager.setCurrentItem(1);
            }
        });
        bartrack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                customViewPager.setCurrentItem(2);
            }
        });

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Intent intent = new Intent(MainActivity.this, NetSearchWordsActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                MainActivity.this.startActivity(intent);
            }
        });
    }

    private void loginRequest(){
        username = (String) sharedPreferencesUtil.getData(mContext,
                SharedPreferencesUtil.USER_NAME,"");
        password = (String) sharedPreferencesUtil.getData(mContext,
                SharedPreferencesUtil.PASS_WORD,"");
        new AsyncTask<Void,Void,Integer>(){

            @Override
            protected Integer doInBackground(Void... voids) {
                int msg;
                try{
                    String Sid = Utils.md5Password(username+password+"ZK");
                    JsonObject obj = HttpUtil.getResposeJsonObject(User.login(username,password,Sid),mContext,true);
                    if(obj==null){
                        return 0;
                    }
                    user = MainApplication.gsonInstance().fromJson(obj,UserBean.class);
                    msg = Integer.valueOf(user.getMsg());
                    LogUtil.d(TAG,"MSG="+msg);
                    String flag = user.getFlag();
                    LogUtil.d(TAG,"flag="+flag);
                    LogUtil.d(TAG,"id="+user.getId());
                    LogUtil.d(TAG,"sid="+user.getSid());
                    MainApplication.id = user.getId();
                    MainApplication.sid = Sid;
                    return msg;
                }catch(Exception e){
                    e.printStackTrace();
                    return 0;
                }
            }

            @Override
            protected void onPostExecute(Integer msg) {
                super.onPostExecute(msg);
                if(msg==1) {//登陆成功
                    requestgetuserinfo = new Requestgetuserinfo();
                    requestgetuserinfo.execute();
                }else if(msg == 11){//账号密码错误
                    password = "";
                    Toast.makeText(mContext,"表示用户名或者密码错误",Toast.LENGTH_SHORT).show();
                }
            }
        }.execute();
    }

    class Requestgetuserinfo extends AsyncTask<Void , Void ,Boolean> {

        @Override
        protected Boolean doInBackground(Void... voids) {
            try{
                JsonObject jsonObject = HttpUtil.getResposeJsonObject(User.getuserinfo(MainApplication.id,MainApplication.sid,MainApplication.id));

                String flag = jsonObject.get("flag").getAsString();
                user = MainApplication.gsonInstance().fromJson(jsonObject.getAsJsonObject("data"),UserBean.class);
                if(flag.equals("1")){
                    return true;
                }else{
                    return  false;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            if(aBoolean){
//                Toast.makeText(mContext,"获取成功",Toast.LENGTH_SHORT).show();
//                username_tv.setText(user.getNickname());
//                username_motto.setText("签名:"+user.getMotto());
//                ImageLoader.getInstance().displayImage(user.getUserimgurl(),head_iv);
                reUserUI();
            }else{
                Toast.makeText(mContext,"获取失败",Toast.LENGTH_SHORT).show();
            }
        }

        public void cancleTask(){
            cancel(true);
            RequestThreadPool.finish();
        }
    }

    private void switchTabs(int position) {
        for (int i = 0; i < tabs.size(); i++) {
            if (position == i) {
                tabs.get(i).setSelected(true);
            } else {
                tabs.get(i).setSelected(false);
            }
        }
    }

    @Override
    public void onConfirm(int currentTheme) {
        if (ThemeHelper.getTheme(MainActivity.this) != currentTheme) {
            ThemeHelper.setTheme(MainActivity.this, currentTheme);
            ThemeUtils.refreshUI(MainActivity.this, new ThemeUtils.ExtraRefreshable() {
                        @Override
                        public void refreshGlobal(Activity activity) {
                            //for global setting, just do once
                            if (Build.VERSION.SDK_INT >= 21) {
                                final MainActivity context = MainActivity.this;
                                ActivityManager.TaskDescription taskDescription = new ActivityManager.TaskDescription(null, null, ThemeUtils.getThemeAttrColor(context, android.R.attr.colorPrimary));
                                setTaskDescription(taskDescription);
                                getWindow().setStatusBarColor(ThemeUtils.getColorById(context, R.color.theme_color_primary));
                            }
                        }

                        @Override
                        public void refreshSpecificView(View view) {
                        }
                    }
            );
        }
        changeTheme();
    }

    @Override
    public void onClick(View v) {
        if(v == login_regitser_layout){
            if(password.isEmpty()) {
                Intent intent = new Intent(mContext, LoginRegisterActivity.class);
                startActivityForResult(intent, LOGIN_REGISTER_REQUEST);
            }else{//查看个人详情
                if(user!=null){
                    Intent intent = new Intent(mContext,UserInfoActivity.class);
                    intent.putExtra("userid",user.getId());
                    intent.putExtra("ismyself",true);
                    startActivity(intent);
                }
            }
        }else if(v == download_layout){
            Intent intent = new Intent(mContext, DownActivity.class);
            startActivity(intent);
        }else if(v == collection_layout){
            Intent intent = new Intent(mContext, CollectionsActivity.class);
            startActivity(intent);
        }else if(v == message_layout){
//            Intent intent = new Intent(mContext,MessageActivity.class);
//            startActivity(intent);
            Toast.makeText(mContext,"敬请期待",Toast.LENGTH_SHORT).show();
        }else if(v == bundAccount_layout){
            Intent intent = new Intent(mContext,AccountSafetyActivity.class);
            startActivity(intent);
        }else if(v == cleanCash_layout){
            Intent intent = new Intent(mContext,CleanCacheActivity.class);
            startActivity(intent);
        }else if(v == about_layout){
            Intent intent = new Intent(mContext,AboutActivity.class);
            startActivity(intent);
        }else if(v == version_layout){
            Intent intent = new Intent(mContext,AboutActivity.class);
            startActivity(intent);
        }else if(v == feedback_layout){
            Intent intent = new Intent(mContext,FeedbackActivity.class);
            startActivity(intent);
        }else if(v == loginOut_layout){
            loginout();
        }else if(v == small_head_iv){
            drawerLayout.openDrawer(Gravity.LEFT);
        }
    }

    private void loginout() {
        username_motto.setVisibility(View.GONE);
        sharedPreferencesUtil.saveData(mContext,sharedPreferencesUtil.PASS_WORD,"");
        password = "";
        username_tv.setText(getString(R.string.loagin_register));
        head_iv.setImageDrawable(getResources().getDrawable(R.drawable.leftbar_ic_bg));
        MainApplication.sid = "";
        MainApplication.id = "";
        Toast.makeText(mContext,"已退出登录",Toast.LENGTH_SHORT).show();
    }


    static class CustomViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragments = new ArrayList<>();

        public CustomViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        public void addFragment(Fragment fragment) {
            mFragments.add(fragment);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // handle item selection
        switch (item.getItemId()) {
            case android.R.id.home: //Menu icon
                drawerLayout.openDrawer(Gravity.LEFT);
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(splashScreen!=null) {
            splashScreen.removeSplashScreen();
        }
        unregisterReceiver(mBroadcastReceiver);
    }

    /**
     * 双击返回桌面
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - time > 1000)) {
                Toast.makeText(this, "再按一次返回桌面", Toast.LENGTH_SHORT).show();
                time = System.currentTimeMillis();
            } else {
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                startActivity(intent);
            }
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments != null) {
            for (Fragment fragment : fragments) {
                if (fragment != null) {
                    fragment.onRequestPermissionsResult(requestCode,permissions,grantResults);
                }
            }
        }
    }

}
